#import "YQPCartListModel.h"

#import "MYShopCarVC.h"
#import "MYShopDetailsVC.h"
#import "MYShopSalesOrderVC.h"
#define kSELECTBTN_BASE_TAG 10100
@interface MYShopCarVC ()<MYGoodCarCellDelegate>

@property (nonatomic, strong) MYShopCarBottonView * bottonView;

/// 当前购物车选中的数据
@property (strong, nonatomic) NSMutableArray *selectGoodsArray;

@property (strong, nonatomic) YQPCartListModel *model;

@property (assign, nonatomic) CGFloat allPrice;

//@property (assign, nonatomic) CGFloat goodsNum;

@property (nonatomic, assign) NSInteger goodsNum;
@end

@implementation MYShopCarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rightItemTitle = kYQLS(@"管理");
    [self.rightItem setTitle:kYQLS(@"管理") forState:(UIControlStateNormal)];
    [self.rightItem setTitle:kYQLS(@"完成") forState:(UIControlStateSelected)];
    [self.rightItem setTitleColor:kAPPMainTitleColor forState:(UIControlStateNormal)];
    self.navigationItem.title = kYQLS(@"购物车");
    //默认总金额
    self.allPrice = 0.00;
    self.bottonView.totalMoneyLb.text = [NSString stringWithFormat:@"%@:%.2f %@",kYQLS(@"总计"),self.allPrice,kYQLS(@"元")];
    self.listTableView.backgroundColor = HexColor(0xFAFAFA);
    [self setupRefresh];
}

-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = UIColor.whiteColor;
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-kHeight_Botton_SafeArea-49-Height_NavBar);
//    kYQREGISTERTABLEVIEWCHeaderFooter([])
    [self.listTableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"kUITableViewHeaderFooterView"];
    kYQREGISTERTABLEVIEWNIBCELL(@"MYGoodCarCell")
    [self.view addSubview:self.bottonView];
    [self.bottonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-kHeight_Botton_SafeArea);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(49);
    }];
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self _setNavShadow];
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self _clearNavShadow];
}

-(void)rightItemAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.bottonView.isManageModel = sender.selected;
    [self totalPrice];
}

- (void)setupRefresh
{
    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getUserCartGoodsApi:YES];
    }];

    self.listTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.dataArr.count < 10) {
            [self.listTableView.mj_footer endRefreshing];
            return ;
        }
        self.page ++;

        [self getUserCartGoodsApi:NO];
    }];
    [self.listTableView.mj_header beginRefreshing];
    self.listTableView.mj_header.automaticallyChangeAlpha = YES;

}
#pragma mark - POST购物车
- (void)getUserCartGoodsApi:(BOOL)isReload
{
    if (isReload) {
        self.page = 1;
    }
    NSMutableDictionary *dic = NSMutableDictionary.new;

    dic[@"page"] = @(self.page);
    dic[@"limit"] = @(10);

    
    [YQPNetWorkingManager sendPostRequest:kPOST_QUERY_CART_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [self stopRefresh];
        if (responseObject.code == 0) {
            if (self.page == 1) {
                [self.dataArr removeAllObjects];
            }
            self.model = [YQPCartListModel mj_objectWithKeyValues:responseObject.data];
            [self.dataArr addObjectsFromArray:self.model.list];
            self.goodsNum = [self.model.totalCount integerValue];
            
            if (self.selectGoodsArray.count > 0) {
                NSMutableArray *tempSelectArr = @[].mutableCopy;
                for (YQPCartModel *goodsModel in self.dataArr) {
                    for (YQPCartModel *selectGoodsModel in self.selectGoodsArray)    {
                        if ([goodsModel.skuId isEqualToString:selectGoodsModel.skuId]) {
                            goodsModel.selectState = YES;
                            [tempSelectArr addObject:goodsModel];
                        }
                    }
                }
                [self.selectGoodsArray removeAllObjects];
                [self.selectGoodsArray addObjectsFromArray:tempSelectArr.copy];
                if (self.selectGoodsArray.count == self.dataArr.count) {
                    self.bottonView.selectAllBtn.selected = YES;
                }else{
                    self.bottonView.selectAllBtn.selected = NO;
                }
                [self totalPrice];
            }

            [self.listTableView reloadData];
            
            if ([self.model.totalPage integerValue] <= self.page) {
                [self.listTableView.mj_footer endRefreshingWithNoMoreData];
            }
        }else{
            YQUITIPSERROR(responseObject.msg)
        }

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
    }];
}

#pragma mark - commitOrder --- 结算---提交普通商品订单事件
- (void)commitOrder
{
    if (self.selectGoodsArray.count == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择商品")];
        return;
    }
    MYShopSalesOrderVC *goodsvc = [MYShopSalesOrderVC new];
    goodsvc.selectGoodArray = self.selectGoodsArray;
    [self.navigationController pushViewController:goodsvc animated:YES];
}
#pragma makr -- 全选
-(void)selectAllAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        for (YQPCartModel *goodsModel in self.dataArr)    {
            goodsModel.selectState = YES;
        }
        [self.selectGoodsArray removeAllObjects];
        [self.selectGoodsArray addObjectsFromArray:self.dataArr];
    }else{
        for (YQPCartModel *goodsModel in self.dataArr)    {
            goodsModel.selectState = NO;
        }
        [self.selectGoodsArray removeAllObjects];
    }
    
    [self totalPrice];
    [self.listTableView reloadData];
}

-(void)selectGoodsAction:(UIButton *)sender {
    NSInteger section = sender.tag - kSELECTBTN_BASE_TAG;
    YQPCartModel *goodsModel = nil;
    if (section < self.dataArr.count) {
        goodsModel = self.dataArr[section];
    }
    
    goodsModel.selectState = !goodsModel.selectState;
    
    if (goodsModel.selectState) {
        [self.selectGoodsArray addObject:goodsModel];
    }else{
        [self.selectGoodsArray removeObject:goodsModel];
    }
    
    if (self.selectGoodsArray.count == self.dataArr.count) {
        self.bottonView.selectAllBtn.selected = YES;
    }else{
        self.bottonView.selectAllBtn.selected = NO;
    }
    
    [self totalPrice];
    [self.listTableView reloadData];
}

#pragma mark 添加收藏事件 --收藏接口
/* toCollectIds (Array[integer], optional): 被收藏的ID-商品/帖子/资讯 ,
type (integer, optional): 收藏类型 ：1->商品收藏 2->帖子收藏 3->资讯收藏
*/

- (void)getLikeCollectionApi
{
    
    if (self.selectGoodsArray.count == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择商品")];
        return;
    }
    
    NSMutableArray *IdArr = @[].mutableCopy;
    for (YQPCartModel *goodsModel in self.selectGoodsArray)    {
        [IdArr addObject:goodsModel.skuId];
    }
    
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"toCollectIds"] = IdArr;//self.selectGoodsArray;
    dic[@"type"] = @"1";
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_ADDMULTIFY_USER_COLLECTIONS_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
             [MBProgressHUD showMessage:kYQLS(@"收藏成功")];
        }else{
            YQUITIPSERROR(responseObject.msg);
        }
        
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error);
    }];
}

#pragma mark - deleteCollections删除购物车商品
- (void)deleteCollections
{
    
    if (self.selectGoodsArray.count == 0) {
        [MBProgressHUD showMessage:kYQLS(@"请选择商品")];
        return;
    }
    
    NSMutableArray *IdArr = @[].mutableCopy;
    for (YQPCartModel *goodsModel in self.selectGoodsArray)    {
        [IdArr addObject:goodsModel.cartItemId];
    }
    
    
    NSMutableDictionary *dic = NSMutableDictionary.new;
    dic[@"cartItemIds"] = [IdArr componentsJoinedByString:@","];//self.selectGoodsArray;
    YQSHOWLOADINGTIPS(kYQLS(@"正在删除..."));
    //@{@"cartItemIds":[self.removeGoodsArray componentsJoinedByString:@","]}
    [YQPNetWorkingManager sendGetRequest:kPOST_DELETE_CART_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            [MBProgressHUD showMessage:kYQLS(@"删除成功")];
            [self.selectGoodsArray removeAllObjects];
            [self getUserCartGoodsApi:YES];
        }else{
            YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error);
        YQHIDELOADINGTIPS
    }];
}
#pragma mark -- 计算价格（总价）
-(void)totalPrice
{
    //每次算完要重置为0，因为每次的都是全部循环算一遍
    self.allPrice = 0;
    //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for (YQPCartModel *goodsModel in self.selectGoodsArray)    {
            self.allPrice +=  [goodsModel.itemNumber intValue] * [goodsModel.price doubleValue];
    }
    
    
    if (self.allPrice < 0.01 && self.allPrice > 0.00) {
        self.allPrice = 0.01;
    }
    //给总价文本赋值
    self.bottonView.totalMoneyLb.text = [NSString stringWithFormat:@"%@:%.2f %@",kYQLS(@"总计"),self.allPrice,kYQLS(@"元")];
    
}

#pragma mark - MYGoodCarCellDelegate---点击事件代理---修改购物车商品数量
- (void)didSelectGoodActionModifyItem:(NSString *)item :(YQPCartModel *)andModel
{
    NSMutableDictionary *dic = NSMutableDictionary.new;
    dic[@"cartItemId"] = andModel.cartItemId;
    dic[@"skuId"] = andModel.skuId;
    dic[@"skuNumber"] = item;
    [YQPNetWorkingManager sendPostRequest:kPOST_MODIFY_CART_NUM_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            //[MBProgressHUD showMessage:@"修改成功"];
            for (YQPCartModel *goodsModel in self.selectGoodsArray)    {
                if ([andModel.skuId isEqualToString:goodsModel.skuId]) {
                    goodsModel.itemNumber = item;
                    [self totalPrice];
                }
            }
            //[self getUserCartGoodsApi:YES];
            [self.listTableView reloadData];
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}

-(void)setGoodsNum:(NSInteger)goodsNum {
    _goodsNum = goodsNum;
    self.navigationItem.title = [NSString stringWithFormat:@"%@(%zd)",kYQLS(@"购物车"),goodsNum];
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    YQPCartModel *model = nil;
    if (indexPath.section < self.dataArr.count) {
        model = self.dataArr[indexPath.section];
    }
     
    MYGoodCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYGoodCarCell"];
    cell.countLb.hidden = YES;
    cell.selectBtn.qmui_outsideEdge = UIEdgeInsetsMake(-20, -10, -20, -10);
    [cell setModel:model];
    cell.delegate = self;
    cell.selectBtn.userInteractionEnabled = YES;
    cell.selectBtn.tag = kSELECTBTN_BASE_TAG + indexPath.section;
    [cell.selectBtn addTarget:self action:@selector(selectGoodsAction:) forControlEvents:(UIControlEventTouchUpInside)];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 124;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YQPCartModel *model = nil;
    if (indexPath.section < self.dataArr.count) {
        model = self.dataArr[indexPath.section];
    }
    MYShopDetailsVC *detailsVC = [[MYShopDetailsVC alloc] init];
    detailsVC.skuId = model.skuId;
    [self.navigationController pushViewController:detailsVC animated:true];
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"kUITableViewHeaderFooterView"];
    footerView.contentView.backgroundColor = HexColor(0xFAFAFA);
    return footerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma makr -- lazy
-(MYShopCarBottonView *)bottonView {
    if (!_bottonView) {
        _bottonView = [MYShopCarBottonView viewFromXib];
        _bottonView.backgroundColor = UIColor.whiteColor;
        _bottonView.layer.shadowColor = HexColorA(0x000000, 0.6).CGColor;//RGB(70, 69, 69).CGColor;
        //2.设置阴影偏移范围
        _bottonView.layer.shadowOffset = CGSizeMake(0, 2);
        //3.设置阴影颜色的透明度
        _bottonView.layer.shadowOpacity = 0.5;
        
        //4.设置阴影半径
        _bottonView.layer.shadowRadius = 4;
        //5.设置阴影路径
        _bottonView.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.navigationController.navigationBar.bounds].CGPath;
        
        [_bottonView.selectAllBtn addTarget:self action:@selector(selectAllAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [_bottonView.moveBtn addTarget:self action:@selector(getLikeCollectionApi) forControlEvents:UIControlEventTouchUpInside];
        [_bottonView.deleteBtn addTarget:self action:@selector(deleteCollections) forControlEvents:UIControlEventTouchUpInside];
        [_bottonView.settlementBtn addTarget:self action:@selector(commitOrder) forControlEvents:UIControlEventTouchUpInside];

    }
    return _bottonView;
}

-(NSMutableArray *)selectGoodsArray {
    if (!_selectGoodsArray) {
        _selectGoodsArray = [NSMutableArray array];
    }
    return _selectGoodsArray;
}
#pragma makr -- lazy end
@end
